package com.ev.k3cloudBusiness.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ev.asl.constant.AslConstant;
import com.ev.common.enums.AuditStatusDict;
import com.ev.custom.dao.DictionaryDao;
import com.ev.custom.domain.DictionaryDO;
import com.ev.custom.domain.MaterielDO;
import com.ev.custom.domain.SupplierDO;
import com.ev.custom.service.MaterielService;
import com.ev.custom.service.SupplierService;
import com.ev.framework.utils.R;
import com.ev.framework.utils.ShiroUtils;
import com.ev.hr.domain.EmployeeInfoDO;
import com.ev.hr.service.EmployeeInfoService;
import com.ev.k3cloud.entity.K3CloudBillQueryEntity;
import com.ev.k3cloud.enums.K3CloudBillFormId;
import com.ev.k3cloud.service.K3CloudService;
import com.ev.k3cloud.service.kingdeeMiddlewareService;
import com.ev.k3cloudBusiness.service.K3ICMOSynService;
import com.ev.k3cloudBusiness.service.K3PurchaseOrderSynService;
import com.ev.k3cloudBusiness.vo.K3ICMOResultsVo;
import com.ev.k3cloudBusiness.vo.K3PurchaseOrderEntryResultsVo;
import com.ev.k3cloudBusiness.vo.K3PurchaseOrderResultsVo;
import com.ev.mes.domain.ProductionPlanDO;
import com.ev.mes.service.ProductionPlanService;
import com.ev.scm.domain.PurchasecontractDO;
import com.ev.scm.domain.PurchasecontractItemDO;
import com.ev.scm.service.PurchasecontractItemService;
import com.ev.scm.service.PurchasecontractService;
import com.ev.system.domain.DeptDO;
import com.ev.system.domain.UserDO;
import com.ev.system.service.DeptService;
import com.ev.system.service.UserService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class K3ICMOSynServiceImpl implements K3ICMOSynService {
    private static final String PRODUCTION_TYPE = "production_type";
    private static final Long PRODUCTION_TYPE_ID= 61L;
    @Autowired
    K3CloudService k3CloudService;
    @Autowired
    ProductionPlanService productionPlanService;

    @Autowired
    DictionaryDao dictionaryDao;

    @Autowired
    DeptService deptService;
    @Autowired
    EmployeeInfoService employeeInfoService;
    @Autowired
    MaterielService materielService;
    @Autowired
    UserService userService;
    @Autowired
    kingdeeMiddlewareService kingdeeMiddlewareService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R ICMOSyn(){
        //查询芯软云生产计划
        List<ProductionPlanDO> productionPlanDOList=productionPlanService.listAll();
        String materialResult=kingdeeMiddlewareService.IcmoAll();
        JSONObject resultObj = JSON.parseObject(materialResult);
        if(!resultObj.getString("code").equals("0"))
        {
            log.info(resultObj.getString("msg"));
            return  R.error(resultObj.getString("msg"));
        }
        List<K3ICMOResultsVo> k3ICMOResultsVos=JSON.parseArray(resultObj.get("data").toString(),K3ICMOResultsVo.class);

        if(k3ICMOResultsVos.size() > 0)
        {
            Long userId = ShiroUtils.getUserId();
            // 获取本地所有的生产计划类型
            List<DictionaryDO> localPurChaseList = dictionaryDao.listByType(PRODUCTION_TYPE);
//        this.handle(k3ICMOResultsVos,localPurChaseList);
            Map<String, Long> localPurChaseMap = localPurChaseList.stream().distinct().collect(Collectors.toMap(DictionaryDO::getName, DictionaryDO::getId, (v1, v2) -> v1));
            // 本地生产计划内码
            List<Long> localIdList = productionPlanDOList.stream().map(ProductionPlanDO::getId).collect(Collectors.toList());
            // K3Cloud生产计划内码
            List<Long> remoteIdList = k3ICMOResultsVos.stream().map(K3ICMOResultsVo::getFInterID).collect(Collectors.toList());
            // 删除的 k3无，本地有
            List<Long> deleteIdList = localIdList.stream().filter(e -> !remoteIdList.contains(e)).collect(Collectors.toList());
            // 修改的（本地库有的，远端库有的）
            List<Long> updateIdList = remoteIdList.stream().filter(localIdList::contains).collect(Collectors.toList());
            // 新增的（本地库无的，远端库有的）
            remoteIdList.removeAll(updateIdList);
            if(deleteIdList.size()>AslConstant.ZERO)
            {
                //批量删除
                List<ProductionPlanDO> productionPlanDOS=productionPlanDOList.stream().filter(e->deleteIdList.contains(e.getId())).collect(Collectors.toList());
                for (ProductionPlanDO productionPlanDO:productionPlanDOS
                ) {
                    productionPlanDO.setDelFlag(AslConstant.ONE);
                }
                productionPlanService.batchUpdate(productionPlanDOS);
                log.info("批量删除");
            }
            if(updateIdList.size()>AslConstant.ZERO)
            {
                //查询芯软云部门
                List<DeptDO> deptDOList=deptService.listForAll();
                //查询芯软云用户
                List<UserDO> userDOList=userService.listAll();
                List<DeptDO> deptDOS;
                List<UserDO> userDOS;
                List<DictionaryDO> dictionaryDOList;
                //批量更新
                List<K3ICMOResultsVo> k3ICMOResultsVoList = k3ICMOResultsVos.stream().filter(e -> updateIdList.contains(e.getFInterID())).collect(Collectors.toList());
                List<ProductionPlanDO> productionPlanDOS=productionPlanDOList.stream().filter(e->updateIdList.contains(e.getId())).collect(Collectors.toList());
                for (ProductionPlanDO productionPlanDO:productionPlanDOS
                ) {
                    K3ICMOResultsVo productionPlanDOS1=k3ICMOResultsVoList.stream().filter(e->(productionPlanDO.getId().equals(e.getFInterID()))).collect(Collectors.toList()).get(0);
                    //单据编号
                    productionPlanDO.setPlanNo(productionPlanDOS1.getFBillNo());
                    //物料ID
                    productionPlanDO.setMaterielId(productionPlanDOS1.getFItemID());
                    //数量
                    productionPlanDO.setPlanCount(productionPlanDOS1.getFQty());
                    //计划开工日期
                    productionPlanDO.setPlanStartTime(productionPlanDOS1.getFPlanCommitDate());
                    //计划完工日期
                    productionPlanDO.setPlanEndTime(productionPlanDOS1.getFPlanFinishDate());
                    //生产类型
                    productionPlanDO.setType(localPurChaseMap.get(productionPlanDOS1.getFType()));
                    productionPlanDO.setBomId(productionPlanDOS1.getFBomInterID());
                    //生产部门
                    productionPlanDO.setProDept(productionPlanDOS1.getFWorkShop());
                    //审核人
                    productionPlanDO.setAuditor(productionPlanDOS1.getFCheckerID());
                    //生产类型(01:成型，02组装)
                    productionPlanDO.setNewType(productionPlanDOS1.getFHeadSelfJ01100());

                    productionPlanDO.setAGroupNumber(BigDecimal.valueOf(productionPlanDOS1.getFHeadSelfJ01101() != null ? productionPlanDOS1.getFHeadSelfJ01101() : AslConstant.ZERO));

                    productionPlanDO.setBGroupNumber(BigDecimal.valueOf(productionPlanDOS1.getFHeadSelfJ01102() != null ? productionPlanDOS1.getFHeadSelfJ01102() : AslConstant.ZERO));

                    productionPlanDO.setCGroupNumber(BigDecimal.valueOf(productionPlanDOS1.getFHeadSelfJ01103() != null ? productionPlanDOS1.getFHeadSelfJ01103() : AslConstant.ZERO));
                    //制单日期
//                productionPlanDO.setCreateTime(productionPlanDOS1.getFCheckDate());
                    //投料单编号
//                productionPlanDO.setBomId(productionPlanDOS1.getFBomInterID());

//                //生产部门
//                deptDOS=deptDOList.stream().filter(e-> e.getName().equals(productionPlanDOS1.getDept())).collect(Collectors.toList());
//                if(deptDOS.size()==0)
//                {
//                    return R.error(productionPlanDOS1.getDept().toString()+"该部门不存在");
//                }
//                productionPlanDO.setProDept(deptDOS.get(0).getDeptId());
                    //制单人
                    userDOS=userDOList.stream().filter(e-> e.getUserId().equals(productionPlanDOS1.getFBillerID())).collect(Collectors.toList());
                    if(userDOS.size()==AslConstant.ZERO)
                    {
                        productionPlanDO.setCreateBy(userId);
                    }
                    if(userDOS.size()>AslConstant.ZERO)
                    {
                        productionPlanDO.setCreateBy(userDOS.get(AslConstant.ZERO).getUserId());
                    }
                    productionPlanDO.setCreateTime(new Date());
                    productionPlanDO.setStatus(231L);
                    productionPlanDO.setUpdateBy(userId);
                    productionPlanDO.setUpdateTime(new Date());
//                productionPlanDO.setAuditor(userId);
                    productionPlanDO.setDelFlag(AslConstant.ZERO);
                }
                productionPlanService.batchUpdate(productionPlanDOS);
                log.info("批量更新");
            }
            if(remoteIdList.size()>0)
            {

                //查询芯软云部门
                List<DeptDO> deptDOList=deptService.listForAll();
                //查询芯软云用户
                List<UserDO> userDOList=userService.listAll();
                List<DeptDO> deptDOS;
                List<UserDO> userDOS;
                List<DictionaryDO> dictionaryDOList;
                //批量插入
                List<K3ICMOResultsVo> k3ICMOResultsVoList = k3ICMOResultsVos.stream().filter(e -> remoteIdList.contains(e.getFInterID())).collect(Collectors.toList());
                List<ProductionPlanDO> productionPlanDOS= Lists.newArrayList();
                for (K3ICMOResultsVo k3ICMOResultsVo:k3ICMOResultsVoList
                ) {
                    ProductionPlanDO productionPlanDO=new ProductionPlanDO();
                    productionPlanDO.setId(k3ICMOResultsVo.getFInterID());
                    //单据编号
                    productionPlanDO.setPlanNo(k3ICMOResultsVo.getFBillNo());
                    //物料ID
                    productionPlanDO.setMaterielId(k3ICMOResultsVo.getFItemID());
                    //数量
                    productionPlanDO.setPlanCount(k3ICMOResultsVo.getFQty());
                    //计划开工日期
                    productionPlanDO.setPlanStartTime(k3ICMOResultsVo.getFPlanCommitDate());
                    //计划完工日期
                    productionPlanDO.setPlanEndTime(k3ICMOResultsVo.getFPlanFinishDate());
                    //生产类型
                    productionPlanDO.setType(localPurChaseMap.get(k3ICMOResultsVo.getFType()));
                    //生产部门
                    productionPlanDO.setProDept(k3ICMOResultsVo.getFWorkShop());
                    productionPlanDO.setBomId(k3ICMOResultsVo.getFBomInterID());
                    //审核人
                    productionPlanDO.setAuditor(k3ICMOResultsVo.getFCheckerID());
                    //生产类型(01:成型，02组装)
                    productionPlanDO.setNewType(k3ICMOResultsVo.getFHeadSelfJ01100());
                    productionPlanDO.setAGroupNumber(BigDecimal.valueOf(k3ICMOResultsVo.getFHeadSelfJ01101() != null ? k3ICMOResultsVo.getFHeadSelfJ01101() : AslConstant.ZERO));
                    productionPlanDO.setBGroupNumber(BigDecimal.valueOf(k3ICMOResultsVo.getFHeadSelfJ01102() != null ? k3ICMOResultsVo.getFHeadSelfJ01102() : AslConstant.ZERO));
                    productionPlanDO.setCGroupNumber(BigDecimal.valueOf(k3ICMOResultsVo.getFHeadSelfJ01103() != null ? k3ICMOResultsVo.getFHeadSelfJ01103() : AslConstant.ZERO));
                    //制单日期
//                productionPlanDO.setCreateTime(k3ICMOResultsVo.getFCheckDate());
                    //投料单编号
//                productionPlanDO.setBom(k3ICMOResultsVo.getFBomInterID());

//                //生产部门
//                deptDOS=deptDOList.stream().filter(e-> e.getName().equals(k3ICMOResultsVo.getDept())).collect(Collectors.toList());
//                if(deptDOS.size()==0)
//                {
//                    return R.error(k3ICMOResultsVo.getDept().toString()+"该部门不存在");
//                }
//                productionPlanDO.setProDept(deptDOS.get(0).getDeptId());
                    //制单人
                    userDOS=userDOList.stream().filter(e-> e.getName().equals(k3ICMOResultsVo.getFBillerID())).collect(Collectors.toList());
                    if(userDOS.size()==AslConstant.ZERO)
                    {
                        productionPlanDO.setCreateBy(userId);
                        // return R.error(productionPlanDOS1.getDept().toString()+"该部门不存在");
                    }
                    if(userDOS.size()>AslConstant.ZERO)
                    {
                        productionPlanDO.setCreateBy(userDOS.get(AslConstant.ZERO).getUserId());
                    }
                    productionPlanDO.setStatus(231L);
                    productionPlanDO.setTecRouteId(146L);
                    productionPlanDO.setUpdateBy(userId);
                    productionPlanDO.setUpdateTime(new Date());
                    productionPlanDO.setDelFlag(AslConstant.ZERO);
                    productionPlanDOS.add(productionPlanDO);
                }
                productionPlanService.batchSave(productionPlanDOS);
                //生成工序计划
                for (ProductionPlanDO productionPlanDO:productionPlanDOS)
                {
                    productionPlanService.issuedPlan(productionPlanDO.getId());
                }
                log.info("批量新增");
            }
        }
        return R.ok();
    }
//    private void handle(List<K3ICMOResultsVo> remoteData, List<DictionaryDO> localPurChaseList) {
//
//        List<String> localPurChaseNameList = localPurChaseList.stream().map(DictionaryDO::getName).collect(Collectors.toList());
//
//        // 获取远端所有的生产类型
//        List<String> remotePurChaseNameList = remoteData.stream().map(K3ICMOResultsVo::getFType).distinct().collect(Collectors.toList());
//
//        List<DictionaryDO> savePurChaseList = Lists.newArrayList();
//
//        remotePurChaseNameList.removeAll(localPurChaseNameList);
//
//        if (remotePurChaseNameList.size() > 0) {
//            DictionaryDO dictDO;
//            for (String s : remotePurChaseNameList) {
//                dictDO = new DictionaryDO();
//                dictDO.setName(s);
//                dictDO.setTypeId(PRODUCTION_TYPE_ID);
//                savePurChaseList.add(dictDO);
//            }
//        }
//        if (savePurChaseList.size() > 0) {
//            // 批量保存
//            dictionaryDao.batchSave(savePurChaseList);
//            localPurChaseList.addAll(savePurChaseList);
//        }
//    }
}
